#include "server.h"
#include <QDataStream>
#include <QTextCodec>
#include <QDebug>
#include <QTcpSocket>
#include <QMap>
#include <QByteArray>
#include <QMessageBox>
Server::Server(QObject *parent)
    : QTcpServer{parent}
{
    //监听端口
    if(listen(QHostAddress::Any,8989))
    {
        qDebug() <<"服务器启动成功";
    }
    else
    {
        qDebug() << "服务器启动失败";
    }

}

void Server::incomingConnection(qintptr socketDescriptor)
{
    auto client = new QTcpSocket(this);
    client->setSocketDescriptor(socketDescriptor);

    //接收用户名
    connect(client,&QTcpSocket::readyRead,this,[this,client](){
        //处理接收的数据
        QByteArray data = client->readAll();
        QString username = QString::fromUtf8(data);
        client->setProperty("username",username);
        m_clients[username] = client;

        emit newClientConnected(client);
    });

    connect(client,&QTcpSocket::disconnected,this,[this,client](){
        QString username = client->property("username").toString();
        m_clients.remove(username);
        qDebug() << "客户端断开：" << username;
    });
}
void Server::handleReadyRead(QTcpSocket *client)
{
    QByteArray data = client->readAll();
    qDebug() << "接收：" << data;

    //检查是否为文件传输
    if (data.startsWith("FILE:"))
    {
        //解析文件名和文件大小
        int colonpos = data.indexOf(':');
        QString fileName = data.mid(5,colonpos - 5);
        qint64 fileSize = data.mid(colonpos + 1).toLong();

        //接收文件数据
        QByteArray fileData;
        while(fileSize > 0)
        {
            QByteArray block = client->read(qMin(fileSize,qint64(1024)));
            fileData.append(block);
            fileSize -=block.size();
        }

        //转发文件数据
        QString sender = client->property("username").toString();
        for (auto it = m_clients.begin(); it != m_clients.end(); ++it)
        {
            if(it.key() != sender && it.value() == client)
            {
                it.value()->write("FILE:");
                it.value()->write(fileName.toUtf8());
                it.value()->write(":");
            }

            QDataStream out(it.value());
            out <<fileData.size();
            it.value()->write(fileData);

        }

    }
    QString username = client->property("username").toString();
    //发送消息给其他客户端
    for(auto it = m_clients.begin(); it !=m_clients.end();it++)
    {
        if(it.key() != username && it.value() == client)
        {
            it.value()->write(data);
        }
    }
}






